package com.platform.modules.cpt.service.impl;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DownloadUtils;
import com.platform.common.utils.Query;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.UUID;
import com.platform.dao.AttachmentDao;
import com.platform.entity.Attachment;
import com.platform.modules.cpt.dao.CptAcceptanceReportDao;
import com.platform.modules.cpt.dto.ProjectInofDto;
import com.platform.modules.cpt.entity.CptAcceptanceEntity;
import com.platform.modules.cpt.entity.CptAcceptanceReportEntity;
import com.platform.modules.cpt.entity.CptAcceptanceReportQualityEntity;
import com.platform.modules.cpt.entity.CptAcceptanceSuperviseReportEntity;
import com.platform.modules.cpt.entity.CptAcceptanceSuperviseReportStampEntity;
import com.platform.modules.cpt.entity.CptAcceptanceSuperviseTeamEntity;
import com.platform.modules.cpt.service.CptAcceptanceReportQualityService;
import com.platform.modules.cpt.service.CptAcceptanceReportService;
import com.platform.modules.cpt.service.CptAcceptanceService;
import com.platform.modules.cpt.service.CptAcceptanceSuperviseReportService;
import com.platform.modules.cpt.service.CptAcceptanceSuperviseTeamService;
import com.platform.modules.prj.entity.PrjProjectEntity;
import com.platform.modules.prj.service.PrjProjectService;
import com.platform.modules.sys.entity.SysOrgEntity;
import com.platform.modules.sys.service.SysOrgService;
import com.platform.util.DocUtil;

@Service
public class CptAcceptanceReportServiceImpl extends ServiceImpl<CptAcceptanceReportDao, CptAcceptanceReportEntity> implements CptAcceptanceReportService {

    private static final Logger logger = LoggerFactory.getLogger(CptAcceptanceReportServiceImpl.class);
    @Autowired
    private CptAcceptanceService cptAcceptanceService;
    @Autowired
    private CptAcceptanceSuperviseReportService cptAcceptanceSuperviseReportService;
    @Autowired
    private CptAcceptanceSuperviseTeamService cptAcceptanceSuperviseTeamService;
    @Autowired
    private CptAcceptanceReportQualityService cptAcceptanceReportQualityService;
    @Autowired
    private DocUtil docUtil;
    @Autowired
    private AttachmentDao attachmentDao;
    @Autowired
    private PrjProjectService prjProjectService;
    @Autowired  
    private SysOrgService sysOrgService;

    @Override
    public boolean save(CptAcceptanceReportEntity entity) {
        if(StringUtils.isBlank(entity.getId())) {
            this.baseMapper.insert(entity);
        }else {
            this.baseMapper.updateById(entity);
        }
        return true;
    }

    @Override
    public Page<CptAcceptanceReportEntity> queryPage(Map<String, Object> params) {
        Page<CptAcceptanceReportEntity> page = new Query<CptAcceptanceReportEntity>(params).getPage();
        List<CptAcceptanceReportEntity> list = baseMapper.selectList(page, params);
        return page.setRecords(list);
    }

    @Override
    public CptAcceptanceReportEntity queryOne(Map<String, Object> params) {
        List<CptAcceptanceReportEntity> list = baseMapper.selectList(params);
        if(list==null || list.isEmpty()){
            return null;
        }else{
            return list.get(0);
        }
    }

    @Override
    public List<CptAcceptanceReportEntity> queryList(Map<String, Object> params) {
        return baseMapper.selectList(params);
    }
    
    @Override
	public Map<String, Object> createJgxmscFile(CptAcceptanceEntity cptAcceptanceEntity, String newFileName) {
		Map<String, Object> result = new HashMap<>();
		
		CptAcceptanceEntity cptAcceptance = cptAcceptanceService.getById(cptAcceptanceEntity.getId());
		if(null==cptAcceptance) {
			throw new BusinessException("未找到工程竣工验收监督申请记录");
		}
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("cptId", cptAcceptanceEntity.getId());
		CptAcceptanceReportEntity cptAcceptanceReportEntity = queryOne(m);
		if(null==cptAcceptanceReportEntity) {
			throw new BusinessException("未找到竣工项目审查记录");
		}
		
		PrjProjectEntity prjProject = prjProjectService.getById(cptAcceptance.getPrjId());
		if(null==prjProject) {
			throw new BusinessException("未找到工程信息");
		}		

		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptAcceptanceEntity.getId(),"CPT_ACCPTANCE_FILES_JGXMSC");
		//生成过签字文件, 且不重新签, 直接返回
		if(list.size()>0 && 1!=cptAcceptanceEntity.getReSign()){
			Attachment attachment = list.get(0);
	        result.put("fileName",attachment.getName());
	        result.put("attId",attachment.getId());
			return result;
		}
		//生成过签字文件, 且重新签, 删除已生成文件
		else if(list.size()>0 && 1==cptAcceptanceEntity.getReSign()) {
			if(null!=list && list.size()>0) {
				for(int i=0; i<list.size(); i++) {
					Attachment attachment = list.get(i);
					docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
				}
			}
		}
        
        //竣工验收 合格时间
        Calendar cal=Calendar.getInstance();
        cal.setTime(cptAcceptanceReportEntity.getReviewDate());
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH);//获取月份
        int day=cal.get(Calendar.DATE);//获取日

        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                
        
        
        //组装参数
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("ag1", prjProject.getPrjName());
		data.put("ag2", prjProject.getAddress());
		data.put("ag3", prjProject.getBuildCorpName());
		data.put("ag4", prjProject.getJglx());
		data.put("ag5", prjProject.getTotalArea());
		data.put("ag6", prjProject.getKcCorpName());
		data.put("ag7", prjProject.getCs());
		data.put("ag8", prjProject.getSjCorpName());
		data.put("ag9", prjProject.getPrjScale());
		data.put("ag10", prjProject.getStCorpName());
		data.put("ag11", sdf.format(prjProject.getPlanStartTime()));
		data.put("ag12", prjProject.getJlCorpName());
		data.put("ag13", sdf.format(prjProject.getPlanCompleteTime()));
		data.put("ag14", prjProject.getSgCorpName());
		data.put("ag15", prjProject.getSgtscph());
		data.put("ag16", prjProject.getGcsgxkzh());
		data.put("ag17", cptAcceptanceReportEntity.getReviewItem1());
		data.put("ag18", cptAcceptanceReportEntity.getReviewItem2());
		data.put("ag19", cptAcceptanceReportEntity.getReviewItem3());
		data.put("ag20", cptAcceptanceReportEntity.getReviewItem4());
		data.put("ag21", cptAcceptanceReportEntity.getReviewItem5());
		data.put("ag22", cptAcceptanceReportEntity.getReviewItem6());
		data.put("ag23", cptAcceptanceReportEntity.getReviewConclusion());
		data.put("ag24", "");
		data.put("ag25", year);
		data.put("ag26", month+1);
		data.put("ag27", day);
		//替换null值
		processMap(data);
		
		//导出PDF
		String ftlFile = "jgys/Jgxmsc.xml";
		String fileName = DownloadUtils.exportPDF(data, ftlFile);
		
		//转换文件对象类型
        FileItem fileItem = createFileItem(fileName + ".pdf", newFileName);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        
        //上传文件
        String attId = docUtil.createAtt(mfile, "CPT_ACCPTANCE_FILES_JGXMSC", cptAcceptanceEntity.getId());
		
	    result.put("fileName",fileName);
	    result.put("attId",attId);
		return result;
	}


	@Override
	public void downloadJgxmscFile(String cptId, HttpServletRequest request, HttpServletResponse response, String attCode) {
		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到竣工项目审查记录文件");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		
		
		InputStream is = docUtil.getFile(attId);
    	
		// 实现文件下载
       byte[] buffer = new byte[1024];
       BufferedInputStream bis = null;
       try {
           bis = new BufferedInputStream(is);
           OutputStream os = response.getOutputStream();
           int i = bis.read(buffer);
           while (i != -1) {
               os.write(buffer, 0, i);
               i = bis.read(buffer);
           }
       }
       catch (Exception e) {
           
       }
       finally {
           if (bis != null) {
               try {
                   bis.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (is != null) {
               try {
               	is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
		
	}

	@Override
	public void signJgxmscFile(HttpServletRequest request, String cptId, String attCode, String FileName) {
				
		//查询并删除所有 竣工项目审查记录
		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptId,attCode);
		if(null!=list && list.size()>0) {
			for(int i=0; i<list.size(); i++) {
				Attachment attachment = list.get(i);
				docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
			}
		}		
    	
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        Map<String, MultipartFile> map = multipartRequest.getFileMap();
        MultipartFile attach = (MultipartFile) map.values().toArray()[0];
        InputStream inputStream = null;
        try {
            inputStream = attach.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String attId2 = UUID.getId();
        docUtil.createAtt(attId2, null, null, attCode, cptId, FileName, inputStream);
	}

	@Override
	public void downloadSignJgxmscFile(String cptId, HttpServletRequest request, HttpServletResponse response,
			String attCode) {

		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到竣工项目审查文件");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		InputStream is = docUtil.getFile(attId);
    	Attachment attachment = attachmentDao.selectById(attId);
    	
    	//实现文件下载
		byte[] buffer = new byte[1024];
		BufferedInputStream bis = null;
		try {
			response.setHeader("content-type", "application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(attachment.getName(), "UTF-8"));
			response.setContentType("application/octet-stream");

			bis = new BufferedInputStream(is);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
    
	
	@Override
	public Map<String, Object> createDwgczlpdFile(CptAcceptanceReportQualityEntity cptAcceptanceReportQualityEntity, String newFileName) {
		Map<String, Object> result = new HashMap<>();
		
		CptAcceptanceEntity cptAcceptance = cptAcceptanceService.getById(cptAcceptanceReportQualityEntity.getCptId());
		if(null==cptAcceptance) {
			throw new BusinessException("未找到工程竣工验收监督申请记录");
		}
		
		CptAcceptanceReportQualityEntity cptAcceptanceReportQuality = cptAcceptanceReportQualityService.getById(cptAcceptanceReportQualityEntity.getId());
		if(null==cptAcceptanceReportQuality) {
			throw new BusinessException("未找到竣工项目审查记录");
		}
		
		PrjProjectEntity prjProject = prjProjectService.getById(cptAcceptance.getPrjId());
		if(null==prjProject) {
			throw new BusinessException("未找到工程信息");
		}		

		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptAcceptanceReportQuality.getId(),"CPT_ACCPTANCE_FILES_DWGCZLPD");
		//生成过签字文件, 且不重新签, 直接返回
		if(list.size()>0 && 1!=cptAcceptanceReportQualityEntity.getReSign()){
			Attachment attachment = list.get(0);
	        result.put("fileName",attachment.getName());
	        result.put("attId",attachment.getId());
			return result;
		}
		//生成过签字文件, 且重新签, 删除已生成文件
		else if(list.size()>0 && 1==cptAcceptanceReportQualityEntity.getReSign()) {
			if(null!=list && list.size()>0) {
				for(int i=0; i<list.size(); i++) {
					Attachment attachment = list.get(i);
					docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
				}
			}
		}
        
        //竣工验收 合格时间
        Calendar cal=Calendar.getInstance();
        cal.setTime(cptAcceptanceReportQuality.getEvalDate());
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH);//获取月份
        int day=cal.get(Calendar.DATE);//获取日

        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        
        String appeQualityStr = "";
        if("1".equals(cptAcceptanceReportQuality.getAppeQuality())) {
        	appeQualityStr = "好";
        }else if("2".equals(cptAcceptanceReportQuality.getAppeQuality())) {
        	appeQualityStr = "一般";
        }else if("3".equals(cptAcceptanceReportQuality.getAppeQuality())) {
        	appeQualityStr = "差";
        }
        
        
        //组装参数
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("ag1", cptAcceptanceReportQuality.getPartNum());
		data.put("ag2", cptAcceptanceReportQuality.getPartAccordNum());
		data.put("ag3", cptAcceptanceReportQuality.getDataNum());
		data.put("ag4", cptAcceptanceReportQuality.getDataAccordNum());
		data.put("ag5", cptAcceptanceReportQuality.getDataIdentifyNum());
		data.put("ag6", appeQualityStr);
		data.put("ag7", cptAcceptanceReportQuality.getEvalConclusion());
		data.put("ag8", cptAcceptanceReportQuality.getBuildCorpResponsibleUserId());
		data.put("ag9", year);
		data.put("ag10", month+1);
		data.put("ag11", day);
		data.put("ag12", cptAcceptanceReportQuality.getProblems());
		//替换null值
		processMap(data);
		
		//导出PDF
		String ftlFile = "jgys/dwgczlpd.xml";
		String fileName = DownloadUtils.exportPDF(data, ftlFile);
		
		//转换文件对象类型
        FileItem fileItem = createFileItem(fileName + ".pdf", newFileName);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        
        //上传文件
        String attId = docUtil.createAtt(mfile, "CPT_ACCPTANCE_FILES_DWGCZLPD", cptAcceptanceReportQuality.getId());
		
	    result.put("fileName",fileName);
	    result.put("attId",attId);
		return result;
	}


	@Override
	public void downloadDwgczlpdFile(String cptId, HttpServletRequest request, HttpServletResponse response, String attCode) {
		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到竣工项目审查记录文件");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		
		
		InputStream is = docUtil.getFile(attId);
    	
		// 实现文件下载
       byte[] buffer = new byte[1024];
       BufferedInputStream bis = null;
       try {
           bis = new BufferedInputStream(is);
           OutputStream os = response.getOutputStream();
           int i = bis.read(buffer);
           while (i != -1) {
               os.write(buffer, 0, i);
               i = bis.read(buffer);
           }
       }
       catch (Exception e) {
           
       }
       finally {
           if (bis != null) {
               try {
                   bis.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (is != null) {
               try {
               	is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
		
	}

	@Override
	public void signDwgczlpdFile(HttpServletRequest request, String cptId, String attCode, String FileName) {
				
		//查询并删除所有 竣工项目审查记录
		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptId,attCode);
		if(null!=list && list.size()>0) {
			for(int i=0; i<list.size(); i++) {
				Attachment attachment = list.get(i);
				docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
			}
		}		
    	
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        Map<String, MultipartFile> map = multipartRequest.getFileMap();
        MultipartFile attach = (MultipartFile) map.values().toArray()[0];
        InputStream inputStream = null;
        try {
            inputStream = attach.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String attId2 = UUID.getId();
        docUtil.createAtt(attId2, null, null, attCode, cptId, FileName, inputStream);
	}

	@Override
	public void downloadSignDwgczlpdFile(String cptId, HttpServletRequest request, HttpServletResponse response,
			String attCode) {

		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到竣工项目审查文件");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		InputStream is = docUtil.getFile(attId);
    	Attachment attachment = attachmentDao.selectById(attId);
    	
    	//实现文件下载
		byte[] buffer = new byte[1024];
		BufferedInputStream bis = null;
		try {
			response.setHeader("content-type", "application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(attachment.getName(), "UTF-8"));
			response.setContentType("application/octet-stream");

			bis = new BufferedInputStream(is);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void downloadGcjgysbgFile(String cptId, HttpServletRequest request, HttpServletResponse response, String attCode, String rebuildFlag) {

		CptAcceptanceEntity cptAcceptance = cptAcceptanceService.getById(cptId);
		if(null==cptAcceptance) {
			throw new BusinessException("未找到工程竣工验收监督申请记录");
		}
		
		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null!=attList && attList.size()>0 && !"1".equals(rebuildFlag)) {
			String attId = null;
			for(int i=0; i<attList.size(); i++) {
				Attachment attachment = attList.get(i);
				attachment.getName();
				attId = attachment.getId();
			}
			InputStream is = docUtil.getFile(attId);
//	    	Attachment attachment = attachmentDao.selectById(attId);
    	
	    	//实现文件下载
			byte[] buffer = new byte[1024];
			BufferedInputStream bis = null;
			try {
				response.setHeader("content-type", "application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("河北省建设工程竣工验收报告.pdf", "UTF-8"));
				response.setContentType("application/octet-stream");
	
				bis = new BufferedInputStream(is);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else {
			//导出PDF
			String ftlFile = "jgys/hbsjsgcjgysbg.xml";
			String fileName = DownloadUtils.exportPDF(new HashMap(), ftlFile);
			
			//转换文件对象类型
	        FileItem fileItem = createFileItem(fileName+".pdf", "河北省建设工程竣工验收报告");
	        MultipartFile mfile = new CommonsMultipartFile(fileItem);
	        
	        //上传文件
	        String attId = docUtil.createAtt(mfile, "CPT_ACCPTANCE_FILES_GCJGYSBG", cptAcceptance.getId());
	        
	        
			BufferedInputStream bis = null;

	        // 接收合并后的pdf文件流对象
	        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	        ByteArrayInputStream swapStream = null;
	        ByteArrayInputStream swapStream2 = null;
	        // 创建PDF合并对象
	        PDFMergerUtility merger = new PDFMergerUtility();
			 try {
			    //1.拼接表头
			    InputStream is1 = docUtil.getFile(attId);
		        ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(toByteArray(is1));	 
		        merger.addSource(byteArrayInputStream1);
		        
		        //2.拼接竣工项目审查
				List<Attachment> attList2 = docUtil.getAttListByAttBusinessIdAndAttCode(cptAcceptance.getId(), "CPT_ACCPTANCE_FILES_JGXMSC");
				if(null!=attList2 && attList2.size()>0) {
					for(int i=0; i<attList2.size(); i++) {
						Attachment attachment = attList2.get(i);
						String _attId = attachment.getId();
					    InputStream is2 = docUtil.getFile(_attId);
				        ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(toByteArray(is2));	
				        merger.addSource(byteArrayInputStream2);
					}
				}
				
				
		        //3.拼接工程竣工质量评定
				Map<String, Object> columnMap = new HashMap<String, Object> ();
				columnMap.put("cptId", cptAcceptance.getId());
				List<CptAcceptanceReportQualityEntity> qualityLlist= cptAcceptanceReportQualityService.queryList(columnMap);
				if(null!=qualityLlist && qualityLlist.size()>0) {
					for(int j=0; j<qualityLlist.size(); j++) {
						List<Attachment> attList3 = docUtil.getAttListByAttBusinessIdAndAttCode(qualityLlist.get(j).getId(), "CPT_ACCPTANCE_FILES_DWGCZLPD");
						if(null!=attList3 && attList3.size()>0) {
							for(int i=0; i<attList3.size(); i++) {
								Attachment attachment = attList3.get(i);
								String _attId = attachment.getId();
							    InputStream is2 = docUtil.getFile(_attId);
						        ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(toByteArray(is2));	
						        merger.addSource(byteArrayInputStream2);
							}
						}
					}
				}

		        //4.拼接竣工验收情况
				List<Attachment> attList3 = docUtil.getAttListByAttBusinessIdAndAttCode(cptAcceptance.getId(), "CPT_ACCPTANCE_FILES_BXJGYSQK1");
				if(null!=attList3 && attList3.size()>0) {
					for(int i=0; i<attList3.size(); i++) {
						Attachment attachment = attList3.get(i);
						String _attId = attachment.getId();
					    InputStream is2 = docUtil.getFile(_attId);
				        ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(toByteArray(is2));	
				        merger.addSource(byteArrayInputStream2);
					}
				}				
				// 设定合并后的输出流对象
				merger.setDestinationStream(outputStream);
			    // 合并PDF
			    merger.mergeDocuments(null);
			    
			    
			    //写入response 实现文件下载
			    swapStream = new ByteArrayInputStream(outputStream.toByteArray());
			    swapStream2 = new ByteArrayInputStream(outputStream.toByteArray());
	        
		    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
		    	byte[] buffer = new byte[1024];			
				response.setHeader("content-type", "application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("河北省建设工程竣工验收报告.pdf", "UTF-8"));
				response.setContentType("application/octet-stream");
				InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
				bis = new BufferedInputStream(swapStream);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
				
				
				//删除之前文件
				List<Attachment> attList4 = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
				if(null!=attList4 && attList4.size()>0) {
					for(int ii=0; ii<attList4.size(); ii++) {
						Attachment attachment = attList4.get(ii);
						docUtil.deleteAtt(attachment.getId());
					}
				}
				
				//写入存储
			    FileItemFactory factory = new DiskFileItemFactory(16, null);
			    FileItem item = factory.createItem("textField", "text/plain", true, "MyFileName");
		        OutputStream os2 = item.getOutputStream();
		        
				bis = new BufferedInputStream(swapStream2);
				buffer = new byte[1024];
				i = bis.read(buffer);
				while (i != -1) {
					os2.write(buffer, 0, i);
					i = bis.read(buffer);
				}
		        MultipartFile mfile2 = new CommonsMultipartFile(item);		        
		        //上传文件
		        String attId2 = docUtil.createAtt(mfile2, "CPT_ACCPTANCE_FILES_GCJGYSBG", cptId);
				
				
				
				
				//写入存储
//				byte[] _buffer = new byte[1024];
//		        int bytesRead = 0;
//		        int s=0;
//		        while ((bytesRead = swapStream2.read(_buffer, 0, 8192)) != -1) {
//		        	System.out.println("============="+ s++);
//		            os2.write(_buffer, 0, bytesRead);
//		        }
//
//		        MultipartFile mfile2 = new CommonsMultipartFile(item);		        
//		        //上传文件
//		        String attId2 = docUtil.createAtt(mfile2, "CPT_ACCPTANCE_FILES_GCJGYSBG", cptId);
//		        //TODO 文件存储, 明天测试, 注意修改上边的1>2逻辑
		        
			}
			catch (Exception e) {
				e.printStackTrace();
			}finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
		}
		
	}
	


	//获取FileItem对象：
	private FileItem createFileItem(String filePath, String newFileName) {
	    FileItemFactory factory = new DiskFileItemFactory(16, null);
	    String textFieldName = "textField";
	    int num = filePath.lastIndexOf(".");
	    String extFile = filePath.substring(num);
	    FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName");
	    File newfile = new File(filePath);
	    int bytesRead = 0;
	    byte[] buffer = new byte[8192];
	    try {
	        FileInputStream fis = new FileInputStream(newfile);
	        OutputStream os = item.getOutputStream();
	        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
	            os.write(buffer, 0, bytesRead);
	        }
	        os.close();
	        fis.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return item;
	}
	
	private void processMap(Map<String,Object> map) {
		//遍历map 
		for(Map.Entry<String, Object> entry : map.entrySet()) {
			//替换Null值, 防止生成doc文件时报错
            if(map.get(entry.getKey())==null) {
            	map.put(entry.getKey(), "");
            }
		}
	}
	
	private static byte[] toByteArray(InputStream input) throws IOException {
	    ByteArrayOutputStream output = new ByteArrayOutputStream();
	    byte[] buffer = new byte[1024*4];
	    int n = 0;
	    while (-1 != (n = input.read(buffer))) {
	        output.write(buffer, 0, n);
	    }
	    return output.toByteArray();
	}

	@Override
	public ProjectInofDto prjInfo(String cptId) {
		CptAcceptanceEntity cptAcceptanceEntity = cptAcceptanceService.getById(cptId);
		if(null==cptAcceptanceEntity) {
			throw new BusinessException("未找到竣工验收申请记录");
		}
		
		PrjProjectEntity prjProject = prjProjectService.getById(cptAcceptanceEntity.getPrjId());
		if(null==prjProject) {
			throw new BusinessException("未找到工程信息");
		}

		Map<String, Object> m = new HashMap<String, Object>();
		m.put("cptId", cptId);
		CptAcceptanceSuperviseReportEntity cptAcceptanceSuperviseReportEntity  = cptAcceptanceSuperviseReportService.queryOne(m);
		if(null==cptAcceptanceSuperviseReportEntity) {
			throw new BusinessException("未找到竣工验收监督报告");
		}
		
		ProjectInofDto projectInofDto = new ProjectInofDto();
		BeanUtils.copyProperties(prjProject, projectInofDto);
		
		projectInofDto.setUnitPrjName(cptAcceptanceEntity.getUnitPrjName());
		projectInofDto.setQualifiedDate(cptAcceptanceSuperviseReportEntity.getQualifiedDate());
		
		if(StringUtils.isNotBlank(prjProject.getBuildCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getBuildCorpId());
			if(null!=org) {
				projectInofDto.setJsOrgName(org.getOrgName());
				projectInofDto.setJsOrgZzdj(org.getZzdj());
				projectInofDto.setJsOrgFddbr(prjProject.getBuildComartiperson());
				projectInofDto.setJsOrgGcxmfzr("项目负责人");
				projectInofDto.setJsOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setJsOrgZgzsbh(org.getZgzsbh());
			}
		}
		if(StringUtils.isNotBlank(prjProject.getSgCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getSgCorpId());
			if(null!=org) {
				projectInofDto.setSgOrgName(org.getOrgName());
				projectInofDto.setSgOrgZzdj(org.getZzdj());
				projectInofDto.setSgOrgFddbr(prjProject.getSgComartiperson());
				projectInofDto.setSgOrgGcxmfzr("项目负责人");
				projectInofDto.setSgOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setSgOrgZgzsbh(org.getZgzsbh());
			}
		}
		if(StringUtils.isNotBlank(prjProject.getJlCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getJlCorpId());
			if(null!=org) {
				projectInofDto.setJlOrgName(org.getOrgName());
				projectInofDto.setJlOrgZzdj(org.getZzdj());
				projectInofDto.setJlOrgFddbr(prjProject.getJlComartiperson());
				projectInofDto.setJlOrgGcxmfzr("项目负责人");
				projectInofDto.setJlOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setJlOrgZgzsbh(org.getZgzsbh());
			}
		}
		if(StringUtils.isNotBlank(prjProject.getKcCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getKcCorpId());
			if(null!=org) {
				projectInofDto.setKcOrgName(org.getOrgName());
				projectInofDto.setKcOrgZzdj(org.getZzdj());
				projectInofDto.setKcOrgFddbr(prjProject.getKcComartiperson());
				projectInofDto.setKcOrgGcxmfzr("项目负责人");
				projectInofDto.setKcOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setKcOrgZgzsbh(org.getZgzsbh());
			}
		}
		if(StringUtils.isNotBlank(prjProject.getSjCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getSjCorpId());
			if(null!=org) {
				projectInofDto.setSjOrgName(org.getOrgName());
				projectInofDto.setSjOrgZzdj(org.getZzdj());
				projectInofDto.setSjOrgFddbr(prjProject.getSjComartiperson());
				projectInofDto.setSjOrgGcxmfzr("项目负责人");
				projectInofDto.setSjOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setSjOrgZgzsbh(org.getZgzsbh());
			}
		}
		if(StringUtils.isNotBlank(prjProject.getJcCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getJcCorpId());
			if(null!=org) {
				projectInofDto.setJcOrgName(org.getOrgName());
				projectInofDto.setJcOrgZzdj(org.getZzdj());
				projectInofDto.setJcOrgFddbr(prjProject.getJcComartiperson());
				projectInofDto.setJcOrgGcxmfzr("项目负责人");
				projectInofDto.setJcOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setJcOrgZgzsbh(org.getZgzsbh());
			}
		}
		if(StringUtils.isNotBlank(prjProject.getStCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getStCorpId());
			if(null!=org) {
				projectInofDto.setStOrgName(org.getOrgName());
				projectInofDto.setStOrgZzdj(org.getZzdj());
				projectInofDto.setStOrgFddbr(prjProject.getStComartiperson());
				projectInofDto.setStOrgGcxmfzr("项目负责人");
				projectInofDto.setStOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setStOrgZgzsbh(org.getZgzsbh());
			}
		}
		if(StringUtils.isNotBlank(prjProject.getYbhntCorpId())) {
			SysOrgEntity org = sysOrgService.getById(prjProject.getYbhntCorpId());
			if(null!=org) {
				projectInofDto.setYbhntOrgName(org.getOrgName());
				projectInofDto.setYbhntOrgZzdj(org.getZzdj());
				projectInofDto.setYbhntOrgFddbr(prjProject.getYbhntComartiperson());
				projectInofDto.setYbhntOrgGcxmfzr("项目负责人");
				projectInofDto.setYbhntOrgZgzsmc(org.getZgzsmc());
				projectInofDto.setYbhntOrgZgzsbh(org.getZgzsbh());
			}
		}
		
		return projectInofDto;
	}
}
